<template>
  <div class="article-tag-selector">
    <!-- 已选标签显示 -->
    <div v-if="selectedTags.length > 0" class="selected-tags">
      <div class="tags-header">
        <span class="label">已选标签 ({{ selectedTags.length }})</span>
        <el-button size="small" type="danger" text @click="clearAllTags"> 清空全部 </el-button>
      </div>
      <div class="tags-list">
        <el-tag
          v-for="tag in selectedTags"
          :key="tag.id"
          :color="tag.color"
          :style="{
            backgroundColor: tag.color,
            color: getTextColor(tag.color),
            borderColor: tag.color
          }"
          closable
          class="selected-tag"
          @close="removeTag(tag.id)"
        >
          {{ tag.name }}
          <span class="tag-weight">(权重: {{ tag.weight }})</span>
        </el-tag>
      </div>
    </div>

    <!-- 标签选择器 -->
    <div class="tag-selector">
      <div class="selector-header">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索标签名称..."
          :prefix-icon="Search"
          clearable
          class="search-input"
          @input="handleSearch"
        />
        <el-select
          v-model="filterType"
          placeholder="标签类型"
          clearable
          class="type-filter"
          @change="handleSearch"
        >
          <el-option label="文章标签" :value="2" />
          <el-option label="通用标签" :value="3" />
        </el-select>
      </div>

      <div v-loading="loading" class="available-tags">
        <div v-if="availableTags.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无可选标签" />
        </div>
        <div v-else class="tags-grid">
          <div
            v-for="tag in availableTags"
            :key="tag.id"
            class="tag-item"
            :class="{ selected: isSelected(tag.id), disabled: isDisabled }"
            @click="!isDisabled && toggleTag(tag)"
          >
            <div class="tag-content">
              <div class="tag-info">
                <div class="tag-color" :style="{ backgroundColor: tag.color }" />
                <div class="tag-details">
                  <span class="tag-name">{{ tag.name }}</span>
                  <span class="tag-meta"> 权重: {{ tag.weight }} | {{ getTagTypeText(tag.type) }} </span>
                </div>
              </div>
              <div class="tag-actions">
                <el-icon v-if="isSelected(tag.id)" class="selected-icon" color="#67c23a">
                  <Check />
                </el-icon>
                <el-icon v-else-if="!isDisabled" class="add-icon" color="#909399">
                  <Plus />
                </el-icon>
              </div>
            </div>
            <div v-if="tag.description" class="tag-description">
              {{ tag.description }}
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="pagination.total > 0" class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.per_page"
            :total="pagination.total"
            :page-sizes="[12, 24, 48]"
            layout="total, sizes, prev, pager, next"
            small
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Search, Plus, Check } from "@element-plus/icons-vue";
import { getTags, type TagInfo } from "@/api/tag-management";

// Props
const props = defineProps<{
  modelValue: TagInfo[];
  maxTags?: number;
  disabled?: boolean;
}>();

// Emits
const emit = defineEmits<{
  "update:modelValue": [tags: TagInfo[]];
  change: [tags: TagInfo[]];
}>();

// 响应式数据
const loading = ref(false);
const searchKeyword = ref("");
const filterType = ref<number>();
const availableTags = ref<TagInfo[]>([]);

// 分页
const pagination = reactive({
  page: 1,
  per_page: 12,
  total: 0
});

// 计算属性
const selectedTags = computed(() => props.modelValue || []);
const isDisabled = computed(() => props.disabled);

// 获取标签列表
const fetchTags = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.page,
      per_page: pagination.per_page,
      name: searchKeyword.value || undefined,
      type: filterType.value,
      status: 1 // 只获取启用的标签
    };

    const response = await getTags(params);
    if (response.code === 200) {
      // 修复数据结构访问问题：使用 response.data.list 而不是 response.data.tags
      const tagsList = response.data?.list || [];
      // 过滤出文章标签和通用标签
      availableTags.value = tagsList.filter(tag => tag.type === 2 || tag.type === 3);
      pagination.total = response.total;
    }
  } catch (error) {
    ElMessage.error("获取标签列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchTags();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.per_page = size;
  pagination.page = 1;
  fetchTags();
};

const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchTags();
};

// 标签操作
const isSelected = (tagId: number) => {
  return selectedTags.value.some(tag => tag.id === tagId);
};

const toggleTag = (tag: TagInfo) => {
  if (isSelected(tag.id)) {
    removeTag(tag.id);
  } else {
    addTag(tag);
  }
};

const addTag = (tag: TagInfo) => {
  if (props.maxTags && selectedTags.value.length >= props.maxTags) {
    ElMessage.warning(`最多只能选择 ${props.maxTags} 个标签`);
    return;
  }

  const newTags = [...selectedTags.value, tag];
  emit("update:modelValue", newTags);
  emit("change", newTags);
};

const removeTag = (tagId: number) => {
  const newTags = selectedTags.value.filter(tag => tag.id !== tagId);
  emit("update:modelValue", newTags);
  emit("change", newTags);
};

const clearAllTags = () => {
  emit("update:modelValue", []);
  emit("change", []);
};

// 工具函数
const getTagTypeText = (type: number) => {
  const typeMap = {
    2: "文章标签",
    3: "通用标签"
  };
  return typeMap[type] || "未知类型";
};

const getTextColor = (backgroundColor: string) => {
  // 简单的颜色对比度计算，决定文字颜色
  const hex = backgroundColor.replace("#", "");
  const r = parseInt(hex.substr(0, 2), 16);
  const g = parseInt(hex.substr(2, 2), 16);
  const b = parseInt(hex.substr(4, 2), 16);
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;
  return brightness > 128 ? "#000000" : "#ffffff";
};

// 组件挂载
onMounted(() => {
  fetchTags();
});
</script>

<style scoped>
.article-tag-selector {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.selected-tags {
  padding: 12px;
  background-color: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.tags-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.label {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-tag {
  display: flex;
  gap: 4px;
  align-items: center;
}

.tag-weight {
  font-size: 11px;
  opacity: 0.8;
}

.tag-selector {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.selector-header {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  flex: 1;
}

.type-filter {
  width: 120px;
}

.available-tags {
  min-height: 200px;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.tags-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
}

.tag-item {
  padding: 12px;
  cursor: pointer;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.2s;
}

.tag-item:hover:not(.disabled) {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgb(64 158 255 / 10%);
}

.tag-item.selected {
  background-color: #f0f9ff;
  border-color: #67c23a;
}

.tag-item.disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.tag-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.tag-info {
  display: flex;
  flex: 1;
  gap: 8px;
  align-items: center;
}

.tag-color {
  flex-shrink: 0;
  width: 16px;
  height: 16px;
  border-radius: 50%;
}

.tag-details {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 2px;
}

.tag-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.tag-meta {
  font-size: 12px;
  color: #909399;
}

.tag-actions {
  display: flex;
  align-items: center;
}

.selected-icon,
.add-icon {
  font-size: 18px;
}

.tag-description {
  margin-top: 8px;
  font-size: 12px;
  line-height: 1.4;
  color: #666;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
</style>
